package com.cn.transfer;

import com.alibaba.druid.pool.DruidDataSource;
import com.cn.transfer.myanno.MyAutowired;
import org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.*;
import org.springframework.core.Ordered;
import org.springframework.core.annotation.Order;

import javax.sql.DataSource;

/**
 * @author pengg
 */

// @Configuration 注解表明当前类是一个配置类
@Configuration
@ComponentScan({"com.cn.transfer"})
@PropertySource({"classpath:jdbc.properties"})
// spring 对 aop 的支持
@EnableAspectJAutoProxy
/*@Import()*/
public class SpringConfig {

    @Value("${jdbc.driver}")
    private String driverClassName;
    @Value("${jdbc.url}")
    private String url;
    @Value("${jdbc.username}")
    private String username;
    @Value("${jdbc.password}")
    private String password;


    @Bean("dataSource")
    public DataSource createDataSource(){
        DruidDataSource druidDataSource = new DruidDataSource();
        druidDataSource.setDriverClassName(driverClassName);
        druidDataSource.setUrl(url);
        druidDataSource.setUsername(username);
        druidDataSource.setPassword(password);
        return  druidDataSource;
    }

    //注意这里要设置成static,不然依赖注入会失效，
    // 因为这个AutowiredAnnotationBeanPostProcessor定义在当前demo类中，
    // 想要拿到自定义的AutowiredAnnotationBeanPostProcessor，就必须实例化demo类
    //但是在实例化demo类LeonAutowired也同时被处理了，
    // 此时还没有自定义的AutowiredAnnotationBeanPostProcessor，因此不认识@LeonAutowired，
    //因此被注入了null。然后等实例化完了之后自定义的AutowiredAnnotationBeanPostProcessor才拿到
    @Bean
    @Order(Ordered.LOWEST_PRECEDENCE - 3)
    @Scope
    public static AutowiredAnnotationBeanPostProcessor beanPostProcessor(){
        AutowiredAnnotationBeanPostProcessor beanPostProcessor = new AutowiredAnnotationBeanPostProcessor();
        // 将自定义的注解注入到 后置处理器中
        beanPostProcessor.setAutowiredAnnotationType(MyAutowired.class);
        return beanPostProcessor;
    }
}
